package com.example.walled_houses.utils;
import com.example.walled_houses.vo.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static com.example.walled_houses.utils.TengXunConstants.*;

public class UploadCos {

    /**
     * (远程服务器)
     * 同时上传多张图片到服务器
     * @param files
     * @return
//     */

    public static Result uploadPhotos(MultipartFile[] files) {
        //Gson gson = new Gson();
        List<String> photoUrl = new ArrayList<>();
        List<String> tPhotoUrl = new ArrayList<>();
        if (files.length <= 5) {
            for (MultipartFile file : files) {
                String url = null;
                String fileName = null;
                String key = null;
                if (file.getSize() / 2048 > 1024) {
                    return Result.fail().message("单张图片大小不能超过2MB");
                } else {
                    String random = String.valueOf(Date.parse(String.valueOf(new Date())));
                    String fileType = file.getContentType();
                    if ("image/jpg".equals(fileType) || "image/png".equals(fileType) || "image/jpeg".equals(fileType)) {
                        //String filePath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\image";
                        //获取图片名
                        fileName = file.getOriginalFilename();
                        //获取图片的后缀名
                        String suffixName = fileName.substring(fileName.lastIndexOf("."));
                        //重新生成图片名字
                        fileName = random + "_" + UUID.randomUUID() + suffixName;
//                        // 1.初始化身份信息
//                        COSCredentials cos = new BasicCOSCredentials(TENGXUN_ACCESSKEY, TENGXUN_SECRETKEY);
//                        // 2.设置bucket的区域
//                        ClientConfig clientConfig = new ClientConfig(new Region(TENGXUN_BUCKET));
//                        // 3.生成cos客户端
//                        COSClient cosClient = new COSClient(cos, clientConfig);
                        COSClient cosClient = createCOS();
                        //bucket的命名规则为{name}-{appid},此处填写的存储桶名称必须为此格式
                        File localFile = null;
                        try {
                            localFile = File.createTempFile("temp", null);
                            file.transferTo(localFile);
                            // 指定要上传的COS路径
                            key = "/" + TENGXUN_PATHURL + "/" + fileName;
                            PutObjectRequest putObjectRequest = new PutObjectRequest(TENGXUN_BUCKETNAME, key, localFile);
                            cosClient.putObject(putObjectRequest);
                            url = TENGXUN_PATHURL + "/" + fileName;
                        } catch (IOException e) {
                            return Result.fail().message("图片上传失败");
                        }
                    } else {
                        return Result.fail().message("图片格式错误");
                    }
                    photoUrl.add(url);
                    tPhotoUrl.add(TENGXUN_PATH + key);
                }
            }
            return Result.ok(tPhotoUrl).message("图片上传成功");
        } else {
            return Result.fail().message("图片上传数量不能超过5张！");
        }
    }


    /**
     * 上传单张图片到服务器
     * @param file
     * @return
     */
    public static Map<Object, String> uploadPhoto(MultipartFile file){
        //Gson gson = new Gson();
        Map<Object, String> map = new HashMap<>();
        if(file.getSize() / 2048 > 1024){
            map.put("code", "201");
            map.put("message", "单张图片上传不能超过2MB！");
            return map;
        }
        String random = String.valueOf(System.currentTimeMillis());
        String fileType = file.getContentType();
        String url = null;
        if("image/jpg".equals(fileType) || "image/jpeg".equals(fileType) || "image/png".equals(fileType)){
            //获取图片名称
            String filename = file.getOriginalFilename();
            String suffixName = filename.substring(filename.lastIndexOf("."));
            filename = random + "_" + UUID.randomUUID() + suffixName;
//            COSCredentials cos = new BasicCOSCredentials(TENGXUN_ACCESSKEY, TENGXUN_SECRETKEY);
//            //设置bucket的区域
//            ClientConfig clientConfig = new ClientConfig(new Region(TENGXUN_BUCKET));
//            //生成cos客户端
//            COSClient cosClient = new COSClient(cos, clientConfig);
            COSClient cosClient = createCOS();
            File localFile = null;
            String key = null;
            try {
                localFile = File.createTempFile("temp", null);
                file.transferTo(localFile);
                key = "/" + TENGXUN_PATHURL + "/" + filename;
                PutObjectRequest putObjectRequest = new PutObjectRequest(TENGXUN_BUCKETNAME, key, localFile);
                cosClient.putObject(putObjectRequest);
                url = TENGXUN_PATHURL + "/" + filename;
            } catch (IOException e) {
                map.put("code", "201");
                map.put("message", "图片上传失败！");
                return map;
            }
        }else {
            map.put("code", "201");
            map.put("message", "图片格式错误！");
            return map;
        }
        map.put("code", "200");
        map.put("message", url);
        return map;
    }


    /**
     * 删除服务器上的图片
     */
    public static void deleteCOS(String key){
        //删除服务器上的图片
        COSClient cosClient = createCOS();
        cosClient.deleteObject(TENGXUN_BUCKETNAME, key);
    }


    private static COSClient createCOS(){
        // 1.初始化身份信息
        COSCredentials cos = new BasicCOSCredentials(TENGXUN_ACCESSKEY, TENGXUN_SECRETKEY);
        // 2.设置bucket的区域
        ClientConfig clientConfig = new ClientConfig(new Region(TENGXUN_BUCKET));
        // 3.生成cos客户端
        return new COSClient(cos, clientConfig);
    }


}